//create by lwy 2017年9月27日11:45:10
var page =0;
var page2 = 0;
var orderNum = 0;
var refundNum = 0;
var orderStateValue = GetQueryString('orderStateValue');

$(function () {
    if(orderStateValue==""||orderStateValue==undefined||orderStateValue==null){
        orderStateValue=''
    }else{
        orderStateValue = GetQueryString('orderStateValue');
        $('.swiper-slide[stateValue='+orderStateValue+']').addClass('active');
        $('.swiper-slide[stateValue='+orderStateValue+']').siblings().removeClass('active');
    }
    if(orderStateValue==12){
        $('#refundBox').empty();
        $('#refundBox').show();
        $('#orderBox').hide();
        page2=0;
        doRefund();
    }else{
        $('#orderBox').empty();
        $('#refundBox').hide();
        $('#orderBox').show();
        page=0;
        doAjax();
    }
})

function doAjax() {
    page++;
    $.ajax({
        url:'/purchaseOrderC/orderList.json',
        dataType:'json',
        data:{
            pageNum:page,
            token:getItem('token'),
            orderStateValue:orderStateValue,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        beforeSend:function(){
            if(page==1){
                $('<div class="loading"><img src="../phoneImg/jiazaizhong.gif"/></div>').appendTo($('#orderBox'));
            }
        },
        success:function (data) {
            if(data.code==1){
                if(page==1){
                    $('#orderBox').empty();
                    if(data.purchaseOrders.length==0){
                        mui('#refreshContainer').pullRefresh().disablePullupToRefresh();
                        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('#orderBox'));
                    }
                }
                var orderData = data.purchaseOrders;
                for(var k=0;k<orderData.length;k++){
                    $('<div class="order_big_box" id="orderBigBox'+orderData[k].id+'">' +
                        '<div class="order-title"><span>订单号</span><span>'+orderData[k].code+'</span></div></div>').appendTo($('#orderBox'));
                    $('<div class="total" id="total'+orderData[k].id+'">\n' +
                        '<span class="total_price">需付款： <small>¥</small><i> '+orderData[k].payMoney+'</i></span>\n' +
                        '<span class="total_count">共'+orderData[k].goodsOrderNum+'件商品&nbsp;&nbsp;&nbsp;'+orderData[k].serviceNum+'项增值服务</span>\n' +
                        '</div>' +
                        '<div id="handleBox'+orderData[k].id+'" zuodanId="'+orderData[k].id+'"></div>'+
                        '<div class="line"></div>').appendTo($('#orderBigBox'+orderData[k].id+''))
                    if(orderData[k].orderStateValue==1){
                        $('<div class="handle_order">' +
                            '<a class="blue_handle payOrder" deliverType="'+orderData[k].deliveryTypeValue+'" payType="'+orderData[k].payTypeValue+'" code="'+orderData[k].code+'" payMoney="'+orderData[k].payMoney+'">去支付</a>' +
                            '</div>').appendTo($('#handleBox'+orderData[k].id+''));
                    }

                    //二级
                    var shopData = orderData[k].shopOrders;
                    var z = '';
                    for(var j=0;j<shopData.length;j++){
                        var certainOrder = '';
                        if(shopData[j].orderStateValue==5){
                            certainOrder = '<div class="handle_order" id="handle2Box'+orderData[k].id+'" zuodanId="'+shopData[j].id+'"><a class="blue_handle certainOrder" certainId="'+shopData[j].id+'">确认收货</a><a class="gray_handle lookOrder" wuliuName="'+shopData[j].expressCompany+'" wuliuNum="'+shopData[j].wayBillNum+'">查看物流</a></div>'
                        }else if(shopData[j].orderStateValue==10){
                            //true表示可以评论
                            if(shopData[j].hasComment){
                                certainOrder = '<div class="handle_order" id="handle2Box'+orderData[k].id+'" zuodanId="'+shopData[j].id+'"><a class="blue_handle commentOrder" href="doComment.html?commentId='+shopData[j].id+'">立即评价</a></div>';
                            }
                        }
                        $('<div class="order order2" zuodanId="'+shopData[j].id+'" orderState="'+shopData[j].orderStateValue+'" id="shop'+shopData[j].id+'">' +
                            '<div class="shopName"><span>'+shopData[j].shopName+'</span>' +
                            '<span class="state">'+shopData[j].orderState+'</span>' +
                            '</div></div>'+certainOrder+'').insertBefore($('#total'+orderData[k].id+''))

                        var goodsData = shopData[j].goodsOrders;
                        //三级
                        for(var i=0;i<goodsData.length;i++){
                            var service = ''
                            if(goodsData[i].serviceNum>0){
                                service = '（增值服务'+goodsData[i].serviceMoney+'元）'
                            }else{
                                service = '';
                            }
                            z = goodsData.length;
                            $('<div class="detailBox mui-clearfix">\n' +
                                '<div class="order-img-box">\n' +
                                '<img src="'+goodsData[i].goodsImg.split(',')[0]+'">\n' +
                                '</div>\n' +
                                '<div class="order-product-box">\n' +
                                '<p class="orderName">'+goodsData[i].goodsName+'</p>\n' +
                                '<span class="price"><small>￥</small>'+goodsData[i].unitPrice+'<small>'+service+'</small><i>×'+goodsData[i].num+'</i></span>\n' +
                                '</div>\n' +
                                '</div>').appendTo($('#shop'+shopData[j].id+''))
                        }
                    }
                }
                orderNum = orderData.length;
            }
            if(data.code==-1){
                window.location.href="login.html"
            }
            if(data.code==0){
                mui.toast(data.msg);
                return;
            }
        }
    })
    return orderNum;
}

//滑动导航
var mySwiper = new Swiper('#topNav', {
    freeMode: true,
    freeModeMomentumRatio: 0.5,
    slidesPerView: 'auto',

});

swiperWidth = mySwiper.container[0].clientWidth
maxTranslate = mySwiper.maxTranslate();
maxWidth = -maxTranslate + swiperWidth / 2

$(".swiper-container").on('touchstart', function(e) {
    e.preventDefault()
})

mySwiper.on('tap', function(swiper, e) {

//	e.preventDefault()

    slide = swiper.slides[swiper.clickedIndex]
    slideLeft = slide.offsetLeft
    slideWidth = slide.clientWidth
    slideCenter = slideLeft + slideWidth / 2
    // 被点击slide的中心点

    mySwiper.setWrapperTransition(300)

    if (slideCenter < swiperWidth / 2) {

        mySwiper.setWrapperTranslate(0)

    } else if (slideCenter > maxWidth) {

        mySwiper.setWrapperTranslate(maxTranslate)

    } else {

        nowTlanslate = slideCenter - swiperWidth / 2

        mySwiper.setWrapperTranslate(-nowTlanslate)

    }

    $("#topNav  .active").removeClass('active')

    $("#topNav .swiper-slide").eq(swiper.clickedIndex).addClass('active');
    orderStateValue = $("#topNav .swiper-slide").eq(swiper.clickedIndex).attr('stateValue');
    mui('#refreshContainer').pullRefresh().scrollTo(0, 0);//滚动到顶部
    mui('#refreshContainer').pullRefresh().refresh(true);
    if($('.mui-pull-caption').html()=='上拉显示更多'){
        $('.mui-pull-caption').html('');
    }
    if(orderStateValue==12){
        $('#refundBox').empty();
        $('#refundBox').show();
        $('#orderBox').hide();
        page2=0;
        doRefund();
    }else{
        $('#orderBox').empty();
        $('#refundBox').hide();
        $('#orderBox').show();
        page=0;
        doAjax();
    }

})

//去支付
mui('body').on('tap','.payOrder',function () {
    var payOrdercode = $(this).attr('code');
    var payMoney = $(this).attr('payMoney');
    var payType = $(this).attr('payType');
    var deliverType = $(this).attr('deliverType');
    setItem('deliveryType',deliverType);
    setItem('payType',payType);
    window.location.href="choosePayWay.html?payMoney="+payMoney+'&code='+payOrdercode;

})

//评价
mui('body').on('tap','.commentOrder',function () {
    window.location.href=$(this).attr('href');
})


//确认收货
mui('body').on('tap','.certainOrder',function () {
    var cancleOrderId = $(this).attr('certainId');
    var btnArray = ['取消', '确定'];
    mui.confirm('请确认已收到货之后再确认订单？', '', btnArray, function(e) {
        if (e.index == 1) {
            $.ajax({
                url:'/purchaseOrderC/confirmReceiptOrder.json',
                dataType:'json',
                data:{
                    token:getItem('token'),
                    shopOrderId:cancleOrderId,
                    companyCode:getItem('companyCode'),
                },
                type:'post',
                beforeSend:function(){
                    $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                },
                success:function (data) {
                    $('.loading2').hide();
                    if(data.code==1){
                        mui.toast('确认收货成功');
                        window.location.reload();
                    }
                    if(data.code==-1){
                        window.location.href="login.html"
                    }
                    if(data.code==0){
                        mui.toast(data.msg);
                        return;
                    }
                }
            })
        } else {

        }
    })
})


//订单详情
mui('body').on('tap','.order2',function () {
    var zuoDanId = $(this).attr('zuodanid');
    var orderState = $(this).attr('orderState');
    window.location.href="orderDetail.html?orderState="+orderState+"&shopOrderId="+zuoDanId;
})

//查看物流
mui('body').on('tap','.lookOrder',function () {
    var wuliuName = $(this).attr('wuliuName');
    var wuliuNum = $(this).attr('wuliuNum');
    window.location.href="http://m.kuaidi100.com/result.jsp?com="+wuliuName+"&nu="+wuliuNum;
})


//上拉加载
mui.init({
    pullRefresh : {
        container:"#refreshContainer",//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        down: {
            contentdown : "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
            contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
            contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
            callback: function () {
                window.location.reload();
                mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
            }
        },
        up : {
            contentrefresh : "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
            contentnomore:'我是有底线的',//可选，请求完毕若没有更多数据时显示的提醒内容；
            callback :function(){
                setTimeout(function () {
                    var numResult = '';
                    if(orderStateValue==12){
                        numResult = doRefund();
                    }else{
                        numResult = doAjax();
                    }
                    if (numResult < 10) {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(true);
                    } else {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(false);
                    }
                }, 1000);
            } //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
        }
    }
});

$('#outline').click(function () {
    window.location.href="userOutlineOrder_v2.html"
})

function doRefund() {
    page2++;
    $.ajax({
        url:'/purchaseOrderC/refundList.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            pageNum:page2,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        beforeSend:function(){
            if(page2==1){
                $('<div class="loading"><img src="../phoneImg/jiazaizhong.gif"/></div>').appendTo($('#refundBox'));
            }
        },
        success:function (data) {
            if(data.code==1){
                if(page2==1){
                    $('#refundBox').empty();
                    if(data.refundList.length==0){
                        mui('#refreshContainer').pullRefresh().disablePullupToRefresh();
                        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('#refundBox'));
                    }
                }
                var refundList = data.refundList;
                for(var i=0;i<refundList.length;i++){
                    $('<div class="order" zuodanId="'+refundList[i].id+'" orderState="12">\n' +
                        '<div class="shopName refundName"><span>'+refundList[i].shopName+'</span><span\n' +
                        'class="mui-icon mui-icon-arrowright"></span><span class="state">'+refundList[i].refundState+'</span></div>\n' +
                        '<div class="detailBox mui-clearfix refundDetailBox">\n' +
                        '<div class="order-img-box"><img src="'+refundList[i].goodsImg.split(',')[0]+'">\n' +
                        '</div><div class="order-product-box">' +
                        '<p class="orderName">'+refundList[i].goodsName+'</p>\n' +
                        '<span class="price">'+refundList[i].specificationName+'</span></div>\n' +
                        '</div><div class="total refundTitle">'+refundList[i].refundType +
                        '</div><div class="handle_order" id="refundhandleBox'+refundList[i].goodsOrderId+'">\n' +
                        '<a class="blue_handle refunddetail" goodsOrderId="'+refundList[i].goodsOrderId+'">查看详情</a>\n' +
                        '</div><div class="refundLine"></div></div>').appendTo($('#refundBox'))
                    if(refundList[i].refundStateValue==1){
                        $('<a class="gray_handle revocation" revocationId="'+refundList[i].id+'">撤销申请</a>').appendTo($('#refundhandleBox'+refundList[i].goodsOrderId+''))
                    }
                }
                refundNum = refundList.length;
                //退款详情
                mui('body').on('tap','.refunddetail',function () {
                    var zuoDanId = $(this).attr('goodsOrderId');
                    var orderState = orderStateValue;
                    window.location.href="orderDetail.html?orderState="+orderState+"&goodsOrderId="+zuoDanId+'&refund=true';
                })
                //撤销申请
                mui('body').on('tap','.revocation',function () {
                    var revocationId = $(this).attr('revocationId');
                    $.ajax({
                        url:'/purchaseOrderC/cancelRefund.json',
                        dataType:'json',
                        data:{
                            token:getItem('token'),
                            refundId:revocationId,
                            companyCode:getItem('companyCode'),
                        },
                        beforeSend:function(){
                            $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                        },
                        type:'post',
                        success:function (data) {
                            $('.loading2').hide();
                            if(data.code==1){
                                window.location.reload();
                            }
                            if(data.code==-1){
                                window.location.href="login.html"
                            }
                            if(data.code==0){
                                mui.toast(data.msg);
                            }
                        }
                    })
                })
            }
            if(data.code==-1){
                window.location.href="login.html"
            }
            if(data.code==0){
                mui.toast(data.msg);
            }
        }
    })
}

//回到首页
document.getElementById('backIndex').addEventListener('tap',function () {
    window.location.href=$(this).attr('href');
})
